package com.tbit.uqbike.webmanager.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Kang
 * @date 2017年12月21日下午3:38:33
 * @description :http调用第三方接口工具类
 */
@Slf4j
public class HttpClientUtils {
    private final static Object syncLock = new Object();
    private static PoolingHttpClientConnectionManager clientConnectionManager = null;
    private static RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
    private static volatile CloseableHttpClient httpClient = null;

    /**
     * 初始化连接
     */
    static {
        try {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslsf).register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
            clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            clientConnectionManager.setMaxTotal(50);
            clientConnectionManager.setDefaultMaxPerRoute(25);
        } catch (Exception e) {
        }
    }

    /**
     * 设置请求头信息
     *
     * @param headers
     * @param request
     * @return
     */
    private static HttpRequest setHeaders(Map<String, Object> headers, HttpRequest request) {
        for (Map.Entry entry : headers.entrySet()) {
            if (!"Cookie".equals(entry.getKey())) {
                request.addHeader((String) entry.getKey(), (String) entry.getValue());
            } else {
                Map<String, Object> Cookies = (Map<String, Object>) entry.getValue();
                for (Map.Entry entry1 : Cookies.entrySet()) {
                    request.addHeader(new BasicHeader("Cookie", (String) entry1.getValue()));
                }
            }
        }
        return request;
    }

    public static CloseableHttpClient getHttpClient() {
        if (httpClient == null) {
            synchronized (syncLock) {
                if (httpClient == null) {
                    CookieStore cookieStore = new BasicCookieStore();
                    BasicClientCookie cookie = new BasicClientCookie("sessionID", "######");
                    cookie.setDomain("#####");
                    cookie.setPath("/");
                    cookieStore.addCookie(cookie);
                    httpClient = HttpClients.custom().setConnectionManager(clientConnectionManager)
                            .setDefaultCookieStore(cookieStore).setDefaultRequestConfig(config).build();
                }
            }
        }
        return httpClient;
    }

    /**
     * post表单请求
     *
     * @param url
     * @param headers
     * @param data
     * @return
     */
    public static String httpPost(String url, Map<String, Object> headers, List<NameValuePair> data) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpRequest request = new HttpPost(url);
        if (headers != null && !headers.isEmpty()) {
            request = setHeaders(headers, request);
        }
        CloseableHttpResponse response = null;
        UrlEncodedFormEntity uefEntity;
        try {
            HttpPost httpPost = (HttpPost) request;
            uefEntity = new UrlEncodedFormEntity(data, "UTF-8");
            httpPost.setEntity(uefEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("httpPost请求超时！", e);
            log.error(e.getMessage(), e);

        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @param headers
     * @return
     */
    public static String httpGet(String url, Map<String, Object> headers) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpRequest httpGet = new HttpGet(url);
        if (headers != null && !headers.isEmpty()) {
            httpGet = setHeaders(headers, httpGet);
        }
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute((HttpGet) httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("httpGet请求超时！");
            log.error(e.getMessage(), e);

        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @param headers
     * @return
     */
    public static InputStream httpGetFile(String url, Map<String, Object> headers) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpRequest httpGet = new HttpGet(url);
        if (headers != null && !headers.isEmpty()) {
            httpGet = setHeaders(headers, httpGet);
        }
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute((HttpGet) httpGet);
            HttpEntity entity = response.getEntity();
            return entity.getContent();
        } catch (Exception e) {
            log.error("httpGet请求超时！");
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("13923589705");
        list.add("13560573199");
        list.add("15360204577");
        list.add("18033363550");
        list.add("13510446332");
        list.add("13432798086");
        list.add("13060507359");
        list.add("15819098559");
        list.add("13790492818");
        list.add("18206607558");
        list.add("18822844208");
        list.add("15019584200");
        list.add("15813330242");
        list.add("13680926845");
        list.add("18128494822");
        list.add("13432735000");
        list.add("18802066620");
        list.add("13927997252");
        list.add("13751922237");
        list.add("15219319465");
        list.add("18946936321");
        list.add("13432778937");
        list.add("13719574623");
        list.add("15019586588");
        list.add("13751929848");
        list.add("15820308117");
        list.add("13071531471");
        list.add("18138173744");
        list.add("13719566032");
        list.add("13765809417");
        list.add("18927920813");
        list.add("13421577422");
        list.add("13560555019");
        list.add("13536453283");
        list.add("13719569886");
        list.add("13421505606");
        list.add("15819058744");
        list.add("18666258519");
        list.add("14715666075");
        list.add("13809800690");
        list.add("15819085305");
        list.add("13430602621");

        /*for (String phone:list) {
            List<NameValuePair> params=new ArrayList<>();
            params.add(new BasicNameValuePair("phone",phone));
            params.add(new BasicNameValuePair("secret","QWERTYUIOP"));
            params.add(new BasicNameValuePair("money","200"));
            params.add(new BasicNameValuePair("accountId","10614"));
            params.add(new BasicNameValuePair("remark","人工结束订单"));
            params.add(new BasicNameValuePair("token","a90c1c6e-c104-467e-9253-5b1e1cf4a665"));
            String json = HttpClientUtils.httpPost("http://admin.uqbike.com/machineBorrow/finishOrder.do", null, params);
            System.out.println(json+"手机号码="+phone);
        }*/
    }

    /**
     * json格式数据提交
     *
     * @param url
     * @param json
     * @throws IOException
     */
    public static String httpJson(String url, String json) throws IOException {
        final String CONTENT_TYPE_TEXT_JSON = "text/json";
        CloseableHttpClient httpClient = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");

        StringEntity se = new StringEntity(json, "UTF-8");
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        CloseableHttpResponse response2 = null;
        response2 = httpClient.execute(httpPost);
        HttpEntity entity2 = null;
        entity2 = response2.getEntity();
        String s2 = EntityUtils.toString(entity2, "UTF-8");

        return s2;

    }

    /**
     * httpPost 请求
     * @param url
     * @param headers
     * @param requestBody
     * @return
     */
    public static String httpPost(String url, Map<String, Object> headers, String requestBody) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpRequest request = new HttpPost(url);
        if (headers != null && !headers.isEmpty()) {
            request = setHeaders(headers, request);
        }
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = (HttpPost) request;
            StringEntity entity = new StringEntity(requestBody, "application/json", "UTF-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (Objects.nonNull(httpEntity)){
                String result = EntityUtils.toString(httpEntity, "utf-8");
                EntityUtils.consume(httpEntity);
                return result;
            }
        }catch (Exception e){
            log.error("httpPost请求调用失败",e);
        }
        return null;
    }

}
